$(function() {
    getUserInfo()


    //点击退出
    $('#btnLogout').on('click', () => {
        //确认退出
        layer.confirm('确定退出登录?', { icon: 3, title: '提示' }, (index) => {
            layer.close(index)
            localStorage.removeItem('token')
            location.href = '/login.html'
        })
    })
})

function getUserInfo() {
    $.ajax({
        method: 'GET',
        url: '/my/userinfo',
        // headers: {
        //     Authorization: localStorage.getItem('token') || ''
        // },
        success(res) {
            if (res.status !== 0) return layui.layer.msg('获取信息失败')
                //调用renderAvatar渲染头像
            renderAvatar(res.data)
        }

    })
}


//渲染
function renderAvatar(user) {
    //获取用户名称
    let name = user.nickname || user.username
        // console.log(name);
    $('#welcome').html('欢迎&nbsp;&nbsp;' + name)
    if (user.user_pic !== null) {
        //渲染图片头像
        $('.layui-nav-img').attr('src', user.user_pic).show()
        $('.text-avatar').hide()
    } else {
        //文本头像
        $('.layui-nav-img').hide()
        let first = name[0].toUpperCase()
        $('.text-avatar').html(first).show()
    }
}